package com.selftaught.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * HttpXmlUtils
 *
 * @author admin
 * @date 2025-10-23
 */
@Component
public class HttpXmlUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpXmlUtils.class);

    /**
     * 发送 XML 格式的 POST 请求
     *
     * @param url        请求地址
     * @param xmlContent XML 请求内容
     * @return 响应字符串 (XML 格式)
     */
    public String postXml(String url, String xmlContent) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        try {
            // 创建 HttpClient 实例
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            // 设置超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    // 连接超时 30 秒
                    .setConnectTimeout(30000)
                    // socket 超时 60 秒
                    .setSocketTimeout(60000)
                    .build();
            httpPost.setConfig(requestConfig);
            // 设置 HTTP 头
            httpPost.setHeader("Content-Type", "application/xml; charset=UTF-8");
            httpPost.setHeader("Accept", "application/xml");
            // 设置请求体
            StringEntity stringEntity = new StringEntity(xmlContent, StandardCharsets.UTF_8);
            httpPost.setEntity(stringEntity);
            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String responseStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                logger.info("接口响应: {}", responseStr);
                return responseStr;
            }
        } catch (Exception e) {
            logger.error("调用接口失败: {}", e.getMessage(), e);
            throw new RuntimeException("调用接口失败: " + e.getMessage());
        } finally {
            // 释放资源
            try {
                if (httpPost != null) {
                    httpPost.releaseConnection();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e) {
                logger.error("释放HTTP资源失败: {}", e.getMessage());
            }
        }
        return null;
    }
}
